05. Intro to CursorLoader
Intro to CursorLoader
Recap
Earthquake Example
At 1:59, Jessica shows that within the EarthquakeLoader class, we had to override the loadInBackground() method. Inside that method, we performed the HTTP network request, so that it would be performed on the background thread.
Here is the code if you'd like to take a closer look:
After the HTTP network request on the background thread is setup, in the EarthquakeActivity class, we implemented the loader callbacks to create the loader, and handle the result that came back in onLoadFinished.
Finally, we initialized the loader in the onCreate() method of the activity and the earthquake data was magically loaded into the app.
Applying this to the Pets App
For the Pets App, we want to use a loader to fetch pet data from the database. Specifically, we want a CursorLoader because our data is in the form of a Cursor.
Similar to network operations, data operations such as reading and writing to the pets table are expensive and time-consuming, so are database operations. Currently we are performing the ContentResolver query on the main thread in the CatalogActivity. But we don’t want to block the UI thread, so a loader allows us to do the operation on a background thread.
As mentioned earlier, the loader is tied to a URI as its source for data. And coincidentally, we have already setup URIs for all our data with the PetProvider!
The loader will automatically requery the underlying data if the database changes; this means the list of pets won't get out of date and we do not have to manually query the database ourselves to check if there was a change.
As we've explored here, CursorLoader is a powerful tool, helping make our lives easier. Let's explore how to implement it in code.